package com.fast.common.upload;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.fast.common.util.ApplicationUtil;
import com.fast.common.util.ImageUtil;

public class UploadServlet extends HttpServlet {

	private Logger logger = LoggerFactory.getLogger(UploadServlet.class);
	/**
	 */
	private static final long serialVersionUID = -5010570395104997970L;

	/*
	 * //成功时 { "error" : 0, "url" : "http://www.example.com/path/to/file.ext" }
	 * //失败时 { "error" : 1, "message" : "错误信息" }
	 * 
	 * @see
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		FileUpload fileUpload = new FileUpload(); // 允许文件最大长度
		fileUpload.setSizeMax(1024 * 1024 * 1024); // 设置内存缓冲大小
		Map<String, Object> map = new HashMap<String, Object>();
		logger.info("开始上传文件");
		try {
			FileItemIterator iterator = fileUpload.getItemIterator(new ServletRequestContext(req));
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				if (!item.isFormField()) {
					String name = item.getName();
					InputStream is = item.openStream();
					String path = ApplicationUtil.getValue("STATIC_FILE_PATH") + getFileName(name);
					logger.info("文件的路径：{}", path);
					
					File dest = new File(path);
					FileUtils.copyInputStreamToFile(is, dest);
					
					BufferedImage images = ImageIO.read(dest);
					if (images == null) {
						FileUtils.forceDeleteOnExit(dest);
						throw new Exception("文件不合法！");
					}
					map.put("error", 0);
					map.put("url", ApplicationUtil.getValue("STATIC_FILE_URL") + getFileName(name));
					map.put("thumb_url", ApplicationUtil.getValue("STATIC_FILE_URL") + "thumb/" + getFileName(name));
					File thumbDir = new File(ApplicationUtil.getValue("STATIC_FILE_PATH") + "thumb/");
					if (!thumbDir.exists()) {
						thumbDir.mkdirs();
					}
					String thumbPath = ApplicationUtil.getValue("STATIC_FILE_PATH") + "thumb/" + getFileName(name);
					FileOutputStream ops = new FileOutputStream(thumbPath);
					BufferedImage buf = ImageUtil.resize(images, 260, ops);
					double height = buf.getHeight();
					map.put("width", "260px");
					map.put("height", height + "px");
				}
			}
		} catch (FileUploadException e) {
			logger.error("", e);
			map.put("error", 1);
			map.put("message", "文件上传文件失败");
		} catch (Exception e) {
			logger.error("", e);
			map.put("error", 1);
			map.put("message","文件不合法");
		}
		logger.info("返回的数据：{}", map);
		OutputStream os = resp.getOutputStream();
		os.write(JSON.toJSONString(map).getBytes("UTF-8"));
		os.flush();
		os.close();
	}

	private String getFileName(String orifilename) {
		if (StringUtils.isBlank(orifilename)) {
			return null;
		}
		StringBuilder str = new StringBuilder();
		try {
			String baseUrl = Base64.encodeBase64String(orifilename.getBytes("UTF-8"));
			int len = baseUrl.length();
			if (len > 20) {
				baseUrl = baseUrl.substring(len - 20);
			}
			str.append("thum");
			str.append(baseUrl);
			str.append("img");
		} catch (UnsupportedEncodingException e) {
		}
		int lstIndex = orifilename.lastIndexOf(".");
		if (lstIndex > 0) {
			String ext = orifilename.substring(lstIndex);
			str.append(ext);
		}
		return str.toString();
	}
}
